﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.OleDb;

namespace LogFileMonitor
{
    public partial class Main : Form
    {
        DateTime dtAlterTime = DateTime.Now.AddMinutes(-100);
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        string msgDatabaseIP = "";
        string msgDataBaseName = "";
        string msgDbUser = "";
        string msgDbPwd = "";
        string msgDatabasePort = "";
        string msgTelNums = "";
        OleDbConnection con;

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            edtMonitorFolder.Text = ConfigurationManager.AppSettings["MonitorFolder"];
            edtFileNameRule.Text = ConfigurationManager.AppSettings["FileNameRule"];
            edtFileExtention.Text = ConfigurationManager.AppSettings["FileExtention"];
            edtFileEncode.Text = ConfigurationManager.AppSettings["FileEncode"];
            edtMinute.Text = ConfigurationManager.AppSettings["Minute"];
            edtSecond.Text = ConfigurationManager.AppSettings["Second"];
            edtIsFixFileName.Checked = ConfigurationManager.AppSettings["IsFixFileName"] == "T";
            edtInsertDb.Checked = ConfigurationManager.AppSettings["IsInsertDb"] == "T";
            edtAlterTitle.Text = ConfigurationManager.AppSettings["AlterTitle"];
            edtAlterMinute.Text = ConfigurationManager.AppSettings["AlterMinute"];
            edtErrKeys.Text = ConfigurationManager.AppSettings["ErrKeys"];
            msgAlter.Text = ConfigurationManager.AppSettings["LastAlterTxt"];
            edtSendMsg.Text = ConfigurationManager.AppSettings["SendMsg"];

            msgDatabaseIP = ConfigurationManager.AppSettings["MsgDbIP"];
            msgDataBaseName = ConfigurationManager.AppSettings["MsgDbName"];
            msgDatabasePort = ConfigurationManager.AppSettings["MsgDbPort"];
            msgDbUser = ConfigurationManager.AppSettings["MsgDbUser"];
            msgDbPwd = ConfigurationManager.AppSettings["MsgDbPsw"];
            msgTelNums = ConfigurationManager.AppSettings["MsgTelNums"];
            //
            System.Net.Dns.GetHostName();
            System.Net.IPAddress[] IP = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
            edtAlterTitle.Items.Add(System.Net.Dns.GetHostName());
            for (int i = 0; i < IP.Length; i++)
			{
                edtAlterTitle.Items.Add(IP[i]);
			}
        }

        private bool verifity()
        {
            if (edtMonitorFolder.Text == "")
            {
                MessageBox.Show("未配置监控文件夹目录。");
                return false;
            }
            else if (edtFileNameRule.Text == "")
            {
                MessageBox.Show("未配置文件命名规则。");
                return false;
            }
            //else if (edtFileExtention.Text == "")
            //{
            //    MessageBox.Show("未配置后缀名。");
            //    edtFileExtention.SelectAll();
            //    return false;
            //}
            else if (edtMinute.Value <= 0 && edtSecond.Value <= 0)
            {
                MessageBox.Show("监控间隔分秒均为配置。");
                edtMinute.Focus();
                return false;
            }
            //
            if (!Directory.Exists(edtMonitorFolder.Text))
            {
                MessageBox.Show("监控文件夹路径不正确。");
                edtMonitorFolder.SelectAll();
                return false;
            }
            //
            return true;
        }
        private bool saveSettings()
        {
            try
            {
                config.AppSettings.Settings["MonitorFolder"].Value = edtMonitorFolder.Text;
                config.AppSettings.Settings["FileNameRule"].Value = edtFileNameRule.Text;
                config.AppSettings.Settings["FileExtention"].Value = edtFileExtention.Text;
                config.AppSettings.Settings["FileEncode"].Value = edtFileEncode.Text;
                config.AppSettings.Settings["Minute"].Value = edtMinute.Value.ToString();
                config.AppSettings.Settings["Second"].Value = edtSecond.Value.ToString();
                config.AppSettings.Settings["IsFixFileName"].Value = edtIsFixFileName.Checked ? "T" : "F";
                config.AppSettings.Settings["IsInsertDb"].Value = edtInsertDb.Checked ? "T" : "F";
                config.AppSettings.Settings["AlterTitle"].Value = edtAlterTitle.Text;
                config.AppSettings.Settings["AlterMinute"].Value = edtAlterMinute.Text;
                config.AppSettings.Settings["ErrKeys"].Value = edtErrKeys.Text;
                config.AppSettings.Settings["LastAlterTxt"].Value = msgAlter.Text;
                config.AppSettings.Settings["SendMsg"].Value = edtSendMsg.Text;

                config.Save(ConfigurationSaveMode.Modified);
                //ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                Log.write("保存配置失败：" + ex.Message);
                return false;
            }
            return true;
        }
        private void btGetMonitFolde_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog monitorFolde = new FolderBrowserDialog() { Description = "请选择监控文件夹的路径："};
            if (monitorFolde.ShowDialog() != DialogResult.OK)
                return;
            edtMonitorFolder.Text = monitorFolde.SelectedPath;
        }

        private void setButtonEnable(bool enable)
        {
            groupBox1.Enabled = enable;
        }

        private void btOk_Click(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));

            if (btOk.Text == "开始监控")
            {
                Log.write("开始监控");
                if (!verifity()) return;
                if (!saveSettings())
                {
                    MessageBox.Show("保存配置信息失败。");
                    return;
                }
                setButtonEnable(false);
                try
                {
                    timer1.Stop();
                    timer1.Interval = (int)edtMinute.Value * 60000 + (int)edtSecond.Value * 1000;
                    timer1.Start();
                }
                catch (Exception ex)
                {
                    Log.write("启动监视失败:" + ex.Message);
                    MessageBox.Show("启动监视失败。"+ex.Message);
                    return;
                }
                this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                btOk.Text = "停止监控";
                this.Visible = false;
            }
            else
            {
                setButtonEnable(true);
                timer1.Stop();
                this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("stop")));
                btOk.Text = "开始监控";
                Log.write("停止监控");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string fileName = "", filePath = "";
            if (edtIsFixFileName.Checked)//固定文件名
                fileName = edtFileNameRule.Text;
            else
            {
                fileName = DateTime.Today.ToString(edtFileNameRule.Text);
            }
            if (edtFileExtention.Text != "")
                fileName += "." + edtFileExtention.Text;
            filePath = edtMonitorFolder.Text + "\\" + fileName;
            if (!File.Exists(filePath))//没有文件跳过本次监控操作
            {
                Log.write("监控文件不存在,跳过本次监测。" + filePath);
                return;
            }
            //
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("working")));
            //
            Encoding encoding;
            switch (edtFileEncode.Text)
            {
                case "系统默认":
                    encoding = Encoding.Default;
                    break;
                case "ASCII":
                    encoding = Encoding.ASCII;
                    break;
                case "UTF-8":
                    encoding = Encoding.UTF8;
                    break;
                case "Unicode":
                    encoding = Encoding.Unicode;
                    break;
                case "GB2312":
                    encoding = Encoding.GetEncoding("gb2312");
                    break;
                default:
                    encoding = Encoding.GetEncoding(edtFileEncode.Text);
                    break;
            }

            Log.write("打开监控文件。" + filePath);

            string[] errKeys = edtErrKeys.Text.Replace("，", ",").Trim(',').Split(',');
            List<string> allLine = new List<string>();
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr = new StreamReader(fs, encoding);
                string strLine = sr.ReadLine();
                while (strLine != null)
                {
                    allLine.Add(strLine);
                    strLine = sr.ReadLine();
                }
                sr.Close();
            }
            catch (Exception ex)
            {
                this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                Log.write("监测失败：" + ex.Message);
                return;
            }
            //
            for (int m = allLine.Count - 1; m >= 0; m--)
            {
                //if(m>37900)
                //    Log.write(m.ToString()+allLine[m]);
                for (int n = 0; n < errKeys.Length; n++)
                {
                    if (errKeys[n] == "")
                        continue;
                    if (allLine[m].Contains(errKeys[n]))
                    {//发现错误
                        Log.write("发现错误关键字：" + allLine[m]);
                        //检查与上一错误是否为同一记录
                        if (allLine[m] == msgAlter.Text)
                        {
                            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                            Log.write("忽略报警1");
                            return;//同一错误不重复处理
                        }
                        //显示错误
                        msgAlter.Text = allLine[m];
                        //记录至配置文件
                        //Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["LastAlterTxt"].Value = allLine[m];
                        config.Save(ConfigurationSaveMode.Modified);
                        //防止短时间内重复报警
                        if (dtAlterTime > DateTime.Now.AddMinutes(-(int)edtAlterMinute.Value))
                        {
                            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                            Log.write("忽略报警2");
                            return;
                        }
                        //报警操作
                        dtAlterTime = DateTime.Now.AddMinutes(-(int)edtAlterMinute.Value);
                        if (edtInsertDb.Checked)
                        {
                            //MessageBox.Show("插入数据库" + allLine[m]);
                            //插入数据库
                            string sql = string.Format("exec BHosPrcAddAlterMessage '{0}','{1}'"
                                , edtAlterTitle.Text.Replace("'", "''"), allLine[m].Substring(0, allLine[m].Length > 60 ? 60 : allLine[m].Length).Replace("'", "''"));
                            SqlHelper.ExecSqlCmdSqlEx(sql);
                            Log.write("插入数据库" + sql);
                            //--发送短信=============================================================================
                            if (edtSendMsg.Checked)
                            {
                                string msgContent=edtAlterTitle.Text.Replace("'", "‘")+" 胶片服务器异常。"+DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                                string guid = Guid.NewGuid().ToString().Replace("-", "");
                                string[] msgTelNum = msgTelNums.Replace("，", ",").Split(',');
                                if (msgTelNum.Length < 1) return;
                                string strSqlTempl = " insert into Message_Items(MESSAGE_ID,AIM_TEL,MESSAGE_TXT,TYPE_ID) values('{0}','{1}','{2}',{3}) ";
                                string sSql = "";
                                for (int i = 0; i < msgTelNum.Length; i++)
                                {
                                    sSql += string.Format(strSqlTempl, guid, msgTelNum[i], msgContent,2);//0:OA 1:检验 2:检查 3:随访
                                }
                                try
                                {
                                    if (!CheckHisCon()) return;
                                    OleDbCommand comMastIndex = new OleDbCommand();
                                    comMastIndex.CommandText = sSql;
                                    comMastIndex.Connection = con;
                                    if (comMastIndex.ExecuteNonQuery() < 1)
                                    {
                                        MessageBox.Show("短信接口调用失败!");
                                        return;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("短信接口异常!" + ex.Message);
                                    return;
                                }
                            }
                            
                            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                            return;
                        }
                        else
                        {
                            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
                            return;
                        }
                    }
                }
            }
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("start")));
        }
        
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Visible = !this.Visible;
            if (this.Visible)
            { 
                this.WindowState = FormWindowState.Normal;
                this.ShowInTaskbar = true;
            }
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                this.ShowInTaskbar = false;
            }
        }

        #region orcalDbm
        private bool OpenHisCon()
        {
            string linkSql = " Provider=MSDAORA.1;Password=" + msgDbPwd +
                ";Persist Security Info=False;User ID=" + msgDbUser +
                "; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + msgDatabaseIP +
                ")(PORT=" + msgDatabasePort + "))(CONNECT_DATA=(SERVICE_NAME = " + msgDataBaseName + ")))";
            con = new OleDbConnection(linkSql);
            try
            {
                con.Open();
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show("短信数据库连接失败 " + e.Message);
                return false;
            }
        }
        private bool CheckHisCon()
        {
            if (con == null)
                return OpenHisCon();
            try
            {
                if (con.State == ConnectionState.Closed || con.State == ConnectionState.Broken)
                {
                    con.Open();
                }
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show("短信数据库连接失败: " + e.Message);
                return false;
            }
        }
        public bool OrcalExecuteNonQuery(string sSql)
        {
            OleDbCommand comInsert = new OleDbCommand();
            comInsert.CommandText = sSql;
            comInsert.Connection = con;
            try
            {
                comInsert.ExecuteNonQuery();
                return true;
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
                return false;
            }
        }
        #endregion

        private void edtSendMsg_CheckedChanged(object sender, EventArgs e)
        {
            if (edtSendMsg.Checked)
            {
                if (msgDatabaseIP == "" || msgDataBaseName == "" || msgDatabasePort == "" || msgDbUser == "" || msgDbPwd == "" || msgTelNums == "")
                {
                    edtSendMsg.CheckState = CheckState.Unchecked;
                    MessageBox.Show("短信通知配置不完整，无法发送短信通知。");
                    return;
                }
            }
        }

    }
}
